package com.zhb.sys.shiro.user.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhb.sys.shiro.model.User;
import com.zhb.sys.shiro.model.UserRole;
import com.github.abel533.utils.StringUtils;
import com.zhb.sys.shiro.user.service.UserService;
import com.zhb.core.utils.UUIDUtil;
import com.zhb.sys.shiro.mapper.UserMapper;
import com.zhb.sys.shiro.mapper.UserRoleMapper;

/**
 * User服务实现。
 * 
 * @author zhb
 *
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	UserRoleMapper userRoleMapper;

	@Override
	public String selectPasswordByUserName(String userName) {
		return userMapper.selectPasswordByUserName(userName);
	}

	@Override
	public List<User> selectUserByCondition(User user) {
		return userMapper.selectUserByCondition(user);
	}

	@Override
	public int insert(User user) {
		int flag = userMapper.insertSelective(user);
		String roles = user.getRoles();
		if (StringUtils.isNotEmpty(roles)) {
			String[] roleArray = roles.split(",");
			for (String roleId : roleArray) {
				UserRole userRole = new UserRole();
				userRole.setId(UUIDUtil.getId());
				userRole.setRoleId(roleId);
				userRole.setUserId(user.getId());
				userRole.setOperateTime(new Date());
				try {
					userRoleMapper.insertSelective(userRole);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		}
		return flag;
	}

	@Override
	public User selectUserById(String id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public int update(User user) {
		String roles = user.getRoles();
		if (StringUtils.isNotEmpty(roles)) {
			String[] roleArray = roles.split(",");
			for (String roleId : roleArray) {
				UserRole userRole = new UserRole();
				userRole.setId(UUIDUtil.getId());
				userRole.setRoleId(roleId);
				userRole.setUserId(user.getId());
				userRole.setOperateTime(new Date());
				try {
					userRoleMapper.insertSelective(userRole);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		}
		return userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public int delete(String id) {
		return userMapper.deleteByPrimaryKey(id);
	}

	@Override
	public User selectUserRoleAndFunctionByUserName(String username) {
		return userMapper.selectUserRoleAndFunctionByUserName(username);
	}

	@Override
	public void saveBatch(List<User> users) {

	}

}